<template>
  <div class="p-1.5 box-border">
    <div class="flex justify-end">
      <a-button type="primary" @click="onGoAddRole">新增角色</a-button>
    </div>
    <a-table :columns="columns" :data-source="roleList" :pagination="false" class="!mt-4" :bordered="true" :loading="loading">

      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <span>
            <a @click="GoEditRole(record)">编辑</a>
            <a-divider type="vertical" />
            <a-popconfirm
              title="确定要删除此角色吗？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="confirmDell(record)"
            >
                      <a>删除</a>
            </a-popconfirm>
          </span>
        </template>
      </template>
    </a-table>
    <a-modal v-model:open="openModal" :title="formValRef.Id == 0 ? '新增角色':'编辑角色'" @ok="onModelOk">
      <a-form ref="formRef" :model="formValRef"  :scroll="{ y: windowHeight - 180 }">
        <a-form-item label="角色名称" name="RoleName" :rules="[{ required: true, message: '请输入角色名称!', trigger: 'change' }]">
          <a-input placeholder="请输入角色名称" v-model:value="formValRef.RoleName"/>
        </a-form-item>
        <a-form-item label="角色权限" name="RouteIds" :rules="[{ required: true, message: '请选择角色权限!' , trigger: 'change'}]">
          <a-tree-select placeholder="请选择角色权限" :tree-data="routeList" 
    allow-clear
    treeDefaultExpandAll
    treeCheckable
    showCheckedStrategy="SHOW_ALL"
     v-model:value="formValRef.RouteIds"
    />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script setup>
import { ref,onMounted,reactive,toRaw,onActivated } from 'vue';
import { message } from 'ant-design-vue';
import { useDotNetBridge,arrTotreeNode, windowHeight } from '../tools/index';

const formValRef = reactive({
  id:0,
  RoleName: '',
  RouteIds: [],
});
const formRef = ref();


const columns = [
  {
    title: 'id',
    dataIndex: 'id',
    key: 'id',
    width: 80,
    align: 'center',
  },
  {
    title: '角色姓名',
    dataIndex: 'name',
    key: 'name',
    align: 'center',
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    align: 'center',
  },
];
const roleList = ref([]);
const routeList = ref([]);
const loading = ref(true);
const openModal = ref(false);
const dotNetBridge = useDotNetBridge();
//新增
const onGoAddRole = () => {
  openModal.value = true;
  formValRef.Id = 0;
  formValRef.RoleName = "";
  formValRef.RouteIds= [];
};

const confirmDell = async e => {
   const result = await dotNetBridge.DellRole(JSON.stringify({RoleId:e.id}));
    const res = JSON.parse(result);
      if(res.code==0){
        message.success("删除成功");
        getAllRoles();
      }else{
        message.error(res.msg);
      }
};

//编辑
const GoEditRole = e => {
  openModal.value = true;
  formValRef.Id = e.id;
  formValRef.RoleName = e.name;
  formValRef.RouteIds= e.routes.map(item=>item.routeId);
};

const onModelOk = () => {
  formRef.value
    .validate()
    .then(async () => {
      if(formValRef.Id==0){
        const result = await dotNetBridge.AddRole(JSON.stringify(formValRef));
        const res = JSON.parse(result);
          if(res.code==0){
            message.success("添加成功");
            openModal.value = false;
            getAllRoles();
          }else{
            message.error(res.msg);
          }
        }else{
          const result = await dotNetBridge.UpdateRole(JSON.stringify(formValRef));
          const res = JSON.parse(result);
            if(res.code==0){
              message.success("更新成功");
              openModal.value = false;
              getAllRoles();
            }else{
              message.error(res.msg);
            }
        }
    })
    .catch(error => {
      console.log('error', error);
    });
};
//获取所有角色
const getAllRoles =async () => {
  loading.value = true;
  try {
    const result = await dotNetBridge.GetAllRole();
    const res = JSON.parse(result);
    loading.value = false;
    if(res.code==0){
      roleList.value = [...res.data];
    }else{
      message.error(res.msg);
    }
  } catch (error) {
     loading.value = false;
    console.log(error);
  }
};

const getAllRoutes =async () => {
  const result = await dotNetBridge.GetAllRoutes();
  const res = JSON.parse(result);
  if(res.code==0){
      routeList.value = arrTotreeNode([...res.data]);
  }
}

const treeChange = (value, label, extra) => {
  formValRef.RouteIds = value.map(item=>item.value);
}


onMounted(() => {
  getAllRoles();
  getAllRoutes();
})

onActivated(()=>{
  console.log("路由切换了");
})
</script>